<?php
namespace Admin\Model;

use Common\Model\CommonModel;

class RechargeModel extends CommonModel {

    public function get_list($where = array(),$order = '',$from =  0,$to = 0,$field = "r.*,l.logistics_name,ul.logistics_name as upper_logistics_name,u.user_nicename,u.user_phone"){
        $list = M("Recharge")->alias("r")->field($field)->where($where)
                ->join("bdt_logistics l ON l.id = r.rid")
                ->join("bdt_logistics ul ON ul.id = l.manager_id",'LEFT')
                ->join("bdt_users u ON u.id = r.uid","LEFT")
                ->order($order)
                ->limit($from , $to)
                ->select();

        return $list;
    }

    public function get_card_list($where = array(),$order = '',$from =  0,$to = 0,$field = "r.*,l.logistics_name,cl.logistics_name as cl_logistics_name,c.number AS card_number,c.vip_name,c.vip_phone,c.vip_plate_number,u.user_nicename,u.user_phone,s.sale_name"){
        $where['r.model'] = 2;
        $list = M("Recharge")->alias("r")->field($field)->where($where)
            ->join("bdt_card c ON c.id = r.rid","inner")
            ->join("bdt_logistics l ON l.id = r.lid","LEFT")
            ->join("bdt_logistics cl ON cl.id = c.lid","LEFT")
            ->join("bdt_sale s ON s.id = r.sale_id","LEFT")
            ->join("bdt_users u ON u.id = r.uid","LEFT")
            ->order($order)
            ->limit($from , $to)
            ->select();
        return $list;
    }

    public function get_sale_manager_list($where = array(),$order = '',$from =  0,$to = 0){
        $list = M("Recharge")->alias("r")->field("r.*,m.sale_manage_name,u.user_nicename,u.user_phone")->where($where)
            ->join("bdt_sale_manager m ON m.id = r.rid","LEFT")
            ->join("bdt_users u ON u.id = r.uid","LEFT")
            ->order($order)
            ->limit($from , $to)
            ->select();
        return $list;
    }

    /**
     * 充值查询接口
     */
    public function get_card_recharge_one($where = array(),$order = '',$field = "r.*,l.logistics_name,cl.logistics_name as cl_logistics_name,c.number AS card_number,c.vip_name,c.vip_phone,c.vip_plate_number,u.user_nicename,u.user_phone,s.sale_name"){
        $where['r.model'] = 2;
        $list = M("Recharge")->alias("r")->field($field)->where($where)
            ->join("bdt_card c ON c.id = r.rid","inner")
            ->join("bdt_logistics l ON l.id = r.lid","LEFT")
            ->join("bdt_logistics cl ON cl.id = c.lid","LEFT")
            ->join("bdt_sale s ON s.id = r.sale_id","LEFT")
            ->join("bdt_users u ON u.id = r.uid","LEFT")
            ->order($order)
            ->find();
        return $list;
    }

    /*老版本-用户数据来源不同*/
    // public function get_list($where = array(),$order = '',$from =  0,$to = 0){
    //     $list = M("Recharge")->alias("r")->field("r.*,l.logistics_name,u.user_nicename,u.user_phone")->where($where)
    //             ->join("bdt_logistics l ON l.id = r.rid")
    //             ->join("bdt_users u ON u.id = r.uid","LEFT")
    //             ->order($order)
    //             ->limit($from , $to)
    //             ->select();

    //     return $list;
    // }

    // public function get_card_list($where = array(),$order = '',$from =  0,$to = 0){
    //     $where['r.model'] = 2;
    //     $list = M("Recharge")->alias("r")->field("r.*,l.logistics_name,c.number AS card_number,car.car_code,u.user_nicename,u.user_phone")->where($where)
    //         ->join("bdt_card c ON c.id = r.rid","inner")
    //         ->join("bdt_logistics l ON l.id = c.lid","LEFT")
    //         ->join("bdt_car car ON car.card_id = c.id","LEFT")
    //         ->join("bdt_users u ON u.id = r.uid","LEFT")
    //         ->order($order)
    //         ->limit($from , $to)
    //         ->select();
    //     return $list;
    // }

    // public function get_sale_manager_list($where = array(),$order = '',$from =  0,$to = 0){
    //     $list = M("Recharge")->alias("r")->field("r.*,m.sale_manage_name,u.user_nicename,u.user_phone")->where($where)
    //         ->join("bdt_sale_manager m ON m.id = r.rid","LEFT")
    //         ->join("bdt_users u ON u.id = r.uid","LEFT")
    //         ->order($order)
    //         ->limit($from , $to)
    //         ->select();
    //     return $list;
    // }
    /*老版本-用户数据来源不同*/

    /**
     * 新增充值记录
     * $model = 1 物流公司充值  =2  会员充值 =3上级销售机构充值
     * op = 2 为审核成功  3为审核失败
     */
    public function insert_data($insert,$model,$op = "", $lid = null,$uid = null){
        if(empty($op)){
            $rid = $insert['rid'];  //物流公司 或 会员ID
            if(empty($rid)){
                return -1;
            }
            $insert['price'] = round($insert['price'],2);
            $insert['general_price'] = round($insert['general_price'],2);
            $insert['self_price'] =  round($insert['self_price'],2);
            $insert['active_price'] =  round($insert['active_price'],2);
            $insert['create_time'] = time();
            // $insert['desc'] = $insert['desc'];
            $insert['model'] = $model;
            $insert['uid'] = $uid?$uid:session('ADMIN_ID');
            $insert['number'] = date("YmdHis").rand(10000,99999);

            $price = round($insert['price']+$insert['general_price']+$insert['self_price']-$insert["active_price"]+$insert['rebate_price'],2);

            if($model == 1){    /*上级物流公司充值*/
                $logistics =  M("Logistics")->where(array("id"=>$rid))->find();
                if(empty($logistics)){
                    return -2;
                }

                $insert['before_balance'] = $logistics['balance'];
                $insert['after_balance'] = round($logistics['balance']+$price,2);

                if($insert["uid"] == 10){   //管理员充值 直接成功
                    $insert["status"] = 2;
                }else{
                    $insert["status"] = 1;
                }

            }elseif($model == 2){   /*会员卡充值*/
                $insert['lid'] = $lid?$lid:get_logistics_id();
                $logistics =  M("Logistics")->where(array("id"=>$lid))->find();
                $card =  M("Card")->where(array("id"=>$rid))->find();
                if(empty($card)){
                    return -2;
                }
                $insert["status"] = 2;
                $insert['before_balance'] = $card['balance'];
                $insert['after_balance'] = round($card['balance']+$price,2);
            }elseif($model == 3){   /*上级销售机构管理充值*/
                $sale_manager_id = $rid;
                $sale_manager = M("SaleManager")->where(array("id"=>$sale_manager_id))->find();
                
                $insert["sale_manager_id"] = $sale_manager_id;
                $insert['before_balance'] = $sale_manager['balance'];
                $insert['after_balance'] = round($sale_manager['balance']+$price,2);

                if($insert["uid"] == 10){   //管理员充值 直接成功
                    $insert["status"] = 2;
                }else{
                    $insert["status"] = 1;
                }
            }elseif($model == 4){    /*二级物流公司充值*/
                $logistics =  M("Logistics")->where(array("id"=>$rid))->find();
                $logistics_upper =  M("Logistics")->where(array("id"=>$logistics['manager_id']))->find();
                if(empty($logistics)){
                    return -2;
                }
                if(empty($logistics_upper) || ($logistics_upper['id'] != '1' && $logistics_upper['balance'] < $price)){
                    return -3;
                }
                $insert['before_balance'] = $logistics['balance'];
                $insert['after_balance'] = round($logistics['balance']+$price,2);
                $insert["status"] = 2;
            }

            $result =  M("Recharge")->add($insert);
            $insert['id'] = M("Recharge")->getLastInsID();

        }elseif(in_array($op,array(2,3)) && $model == 1){  /*上级物流公司充值审核*/
            $logistics = array();
            $recharge_id = $insert["id"];
            $recharge = M("Recharge")->where(array("id"=>$recharge_id))->find();

            if(empty($recharge) || $recharge["model"] != 1){
                // 充值信息出错
                return -3;
            }

            $result = M("Recharge")->where(array("id"=>$recharge_id))->save(array("status"=>$op));
            $logistics["id"] = $recharge["rid"];
            $insert = $recharge;

        }elseif(in_array($op,array(2,3)) && $model == 3){  /*上级消费机构充值审核*/
            $sale_manager_id = $insert['rid'];
            $sale_manager = M("SaleManager")->where(array("id"=>$sale_manager_id))->find();

            $recharge_id = $insert["id"];
            $recharge = M("Recharge")->where(array("id"=>$recharge_id))->find();

            $result = M("Recharge")->where(array("id"=>$recharge_id))->save(array("status"=>$op));
            if ($result) {
                $insert["status"] = 2;
            }
        }else{  //数据参数有误，不存在需要操作的内容
            return -4;
        }

        if($result && ($insert["status"] == 2 || $op == 2)){    /*充值审核通过*/
            if($model == 1){
                //加入账单记录
                D("Logistics/LogisticsBill")->insert_data($logistics['id'],$insert['price'],2);
                if(!empty($insert['general_price'])){
                    D("Logistics/LogisticsBill")->insert_data($logistics['id'],$insert['general_price'],5);
                }
                return $result;
            }elseif($model == 2){
                $lid = $logistics['id'];
                M("Card")->where(array("id"=>$card['id']))->save(array("balance"=>round($card['balance']+$price,2)));
                D("Logistics/LogisticsBill")->insert_data($lid,$insert['price'],3);
                //激活充值赠送
                if(!empty($insert['active_price'])){
                    //D("Logistics/LogisticsBill")->insert_data($lid,$insert['active_price'],4);
                }
                //卡片充值赠送账单
                $give_price = $insert['self_price'];
                if(!empty($give_price)){
                    D("Logistics/LogisticsBill")->insert_data($lid,$give_price,6);
                }
                return $result;
            }elseif($model == 3){
//                 M("SaleManager")->where(array("id"=>$sale_manager_id))->save(array("balance"=>round($sale_manager['balance']+$insert['price'],2)));
                 $result = D("Admin/SaleManagerBill")->insert_data($sale_manager_id,$insert['price'],1);
                return $result;
            }elseif($model == 4){
                $flag = D("Logistics/LogisticsBill")->insert_data($logistics_upper['id'], $insert['price'] * -1, 2);
                if ($flag > 0) {
                    D("Logistics/LogisticsBill")->insert_data($logistics['id'],$insert['price'],2);
                    if(!empty($insert['general_price'])){
                        D("Logistics/LogisticsBill")->insert_data($logistics['id'],$insert['general_price'],5);
                    }
                    return $result;
                }else{
                    return -5;
                }
                
            }
        }elseif($result && ($insert["status"] == 1)){   /*创建充值*/
            if ($model == 1) {  // 上级物流公司充值审核流程
                $flag = D('Examine')->to_examine($insert,'logistics_recharge');
            }elseif ($model == 3) {  // 上级消费机构充值审核流程
                $flag = D('Examine')->to_examine($insert,'sale_manager_recharge');
            }

            return $result;
        }elseif($result && ($insert["status"] == 3 || $op == 3)){   /*充值审核不通过*/

            return $result;
        }else{
            // 充值失败
            return -5;
        }
    }

    /**
     * 新增充值记录
     * $model = 1 物流公司充值  =2  会员充值 =3上级销售机构充值
     * op = 2 为审核成功  3为审核失败
     */
    public function pre_insert_data($insert,$model,$op = "", $lid = null,$uid = null){
        $rid = $insert['rid'];  //物流公司 或 会员ID
        if(empty($rid)){
            return -1;
        }

        $admin_card_give_price = get_config_by_key('admin_card_give_price');    //管理员充值赠送金额
        $logistics_card_give_price = get_config_by_key('logistics_card_give_price');    //管理员开发费

        if ($insert['sale_id']) {
            $sale = M("Sale")->field('s.*, sm.sale_manage_name, sm.balance as upper_balance, sm.give_percent')->alias('s')->join("bdt_sale_manager sm ON sm.id = s.sale_manager_id","LEFT")->where(array("s.id"=>$insert['sale_id']))->find();
            $sale_give_percent = $sale['give_percent'];
            $insert['self_price'] = $insert['price'] * $sale_give_percent / 100;
            $insert['general_price'] = $admin_card_give_price;
        }else{
            $insert['general_price'] = $admin_card_give_price;
            $insert['self_price'] = $logistics_card_give_price;
        }

        $insert['price'] = round($insert['price'],2);
        $insert['general_price'] = round($insert['general_price'],2);
        $insert['self_price'] =  round($insert['self_price'],2);
        $insert['active_price'] =  round($insert['active_price'],2);
        $insert['create_time'] = time();
        $insert['model'] = $model;
        $insert['uid'] = $uid?$uid:session('ADMIN_ID');
        $insert['number'] = date("YmdHis").rand(10000,99999);
        $insert['rebate_price'] = round($insert['rebate_price'],2);

        $insert['lid'] = $lid?$lid:get_logistics_id();
        $result =  M("Recharge")->add($insert);

        if($result){
            return $insert;
        }else{
            return -3;
        }
    }

    public function update_status($recharge_number){
        $recharge = $this->where(array('number'=>$recharge_number))->find();

        if (!empty($recharge) && $recharge['status'] == 1) {

            $rid = $recharge['rid'];  //物流公司 或 会员ID
            if(empty($rid)){
                return -1;
            }

            $price = round($recharge['price']+$recharge['general_price']+$recharge['self_price']-$recharge["active_price"]+$recharge['rebate_price'],2);
            
            $lid = $recharge['lid'];

            $logistics =  M("Logistics")->where(array("id"=>$lid))->find();
            $card =  M("Card")->where(array("id"=>$rid))->find();
            if(empty($card)){
                return -2;
            }
            $recharge_update["status"] = 2;
            $recharge_update['before_balance'] = $card['balance'];
            $recharge_update['after_balance'] = round($card['balance']+$price,2);

            $result =  M("Recharge")->where(array('number'=>$recharge_number))->save($recharge_update);
            if($result){    //管理员充值或审核成功进入账单
                
                M("Card")->where(array("id"=>$card['id']))->save(array("balance"=>round($card['balance']+$price,2)));
                D("Logistics/LogisticsBill")->insert_data($lid,$recharge['price'],3);
                //激活充值赠送
                if(!empty($recharge['active_price'])){
                    //D("Logistics/LogisticsBill")->insert_data($lid,$recharge['active_price'],4);
                }
                //卡片充值赠送账单
                if(!empty($recharge['self_price']) && $recharge['self_price']>0){
                    $give_price = $recharge['self_price'];
                    D("Logistics/LogisticsBill")->insert_data($lid,$give_price,6);
                }

                $card_update =array("recharge_num"=>$card['recharge_num']+1);
                if($card['recharge_num'] == 0){
                    $card_update['is_active'] = 1;
                    $card_update['active_price'] = $recharge['active_price'];
                    M("Logistics")->where(array("id"=>$logistics['id']))->save(array('active_card_num'=>$logistics['active_card_num']+1));
                }
                M("Card")->where(array("id"=>$card['id']))->save($card_update);

                return $recharge;
            }else{
                return -3;
            }
        }
    }


    /**
     * APP 使用
     * 新增充值记录
     * $model = 1 物流公司充值  =2  会员充值 =3上级销售机构充值
     * op = 2 为审核成功  3为审核失败
     */
    public function app_pre_insert($insert,$model){
        $rid = $insert['rid'];  //物流公司 或 会员ID
        if(empty($rid)){
            return -1;
        }

        $admin_card_give_price = get_config_by_key('admin_card_give_price');    //管理员充值赠送金额
        $logistics_card_give_price = get_config_by_key('logistics_card_give_price');    //管理员开发费


        $insert['general_price'] = $admin_card_give_price;
        $insert['self_price'] = $logistics_card_give_price;

        $insert['price'] = round($insert['price'],2);
        $insert['general_price'] = round($insert['general_price'],2);
        $insert['self_price'] =  round($insert['self_price'],2);
        $insert['active_price'] =  round($insert['active_price'],2);
        $insert['create_time'] = time();
        $insert['model'] = $model;
        $insert['uid'] = 0;
        $insert['number'] = date("YmdHis").rand(10000,99999);
        $insert['rebate_price'] = round($insert['rebate_price'],2);

        $insert['lid'] =0;
        $result =  M("Recharge")->add($insert);

        if($result){
            return $insert;
        }else{
            return -3;
        }
    }


    /**
     * @param $card_number
     * @param $price
     * @param $order_number
     * @return int|mixed
     * 充值回调更新
     * -1 卡不存在
     * -2 充值记录不存在
     * -3 金额有误
     * -4 回调失败
     *
     */
    public function app_update_status($card_number,$price,$order_number){
        $card =  M("Card")->where(array("number"=>$card_number))->find();
        if(empty($card)){
            return -1;
        }
        $recharge = $this->where(array('number'=>$order_number))->find();
        if(empty($recharge)){
            return -2;
        }
        if(round($recharge['price'],2) != round($price,2)){
            return -3;
        }
        $price = round($recharge['price']+$recharge['general_price']+$recharge['self_price']-$recharge["active_price"]+$recharge['rebate_price'],2);
        $recharge_update["status"] = 2;
        $recharge_update['before_balance'] = $card['balance'];
        $recharge_update['after_balance'] = round($card['balance']+$price,2);

        if ($recharge['status'] == 1) {
            $result =  M("Recharge")->where(array('id'=>$recharge['id']))->save($recharge_update);
            if($result){    //管理员充值或审核成功进入账单
                M("Card")->where(array("id"=>$card['id']))->save(array("balance"=>round($card['balance']+$price,2)));

                $lid = $recharge['lid'];
                if(!empty($lid) && $lid>0){
                    $logistics =  M("Logistics")->where(array("id"=>$lid))->find();
                    //充值账单
                    D("Logistics/LogisticsBill")->insert_data($lid,$recharge['price'],3);
                    //卡片充值赠送账单
                    if(!empty($recharge['self_price']) && $recharge['self_price']>0){
                        D("Logistics/LogisticsBill")->insert_data($lid,$recharge['self_price'],6);
                    }
                    M("Logistics")->where(array("id"=>$lid))->save(array('active_card_num'=>$logistics['active_card_num']+1));
                }

                $card_update =array("recharge_num"=>$card['recharge_num']+1);
                if($card['recharge_num'] == 0){
                    $card_update['is_active'] = 1;
                    $card_update['active_price'] = $recharge['active_price'];
                }
                M("Card")->where(array("id"=>$card['id']))->save($card_update);

                return $recharge_update;
            }else{
                return -4;
            }
        }else{
            return $recharge_update;
        }
    }
}